<?php

namespace application\attachment\controller;

use ticky\upload;

class api extends auth {

    private $uid;
    private $roleid;

    function __construct() {
        parent::__construct();
        $this->uid = session('uid');
        $this->roleid = session('roleid');
        //判断是否登录
        if ($this->uid == 0) {
            showmsg(L('login_website'), url('/admin/member/index'), 1);
        }
    }

    /**
     * 上传框
     */
    public function upload_box() {
        $pid = isset($_GET['pid']) ? $_GET['pid'] : 'uploadfile';
        $module = isset($_GET['module']) ? $_GET['module'] : '';
        $t = isset($_GET['t']) ? intval($_GET['t']) : 1; //上传类型，1为图片类型
        $n = isset($_GET['n']) ? 20 : 1;  //上传数量
        $s = round(10240 / 1024, 2) . 'MB';  //允许上传附件大小

        if ($t == 1) {
            $type = '*.jpg; *.jpeg; *.png; *.gif;';
        } else {
            $type = '*.' . join(',*.', $this->_get_upload_types());
        }
        $search = array('uid' => 1);
        $ret = db('attachment')->where($search)->order('attachid DESC')->newpage();
        foreach ($ret['items'] as $row) {
            $thum = SERVER_PORT . HTTP_HOST . $row['attachment'] . $row['filename'];
            if (!is_file(ROOT_PATH . $row['attachment'] . $row['filename'])) {
                $thum = "/static/common/img/nopic.jpg";
            }
            $row['imgfile'] = '<li><a href="javascript:;" onclick="javascript:album_cancel(this)">'
                    . '<img class="img_src" src="' . $thum . '" path="' . $row['attachment'] . $row['filename'] . '">'
                    . '<img src="/static/common/img/checked.gif" class="checkd hidden"></a></li>';

            $data[] = $row;
        }
        $this->assign('page', $ret['page']);
        $this->assign('items', $data);

        $this->assign('module', $module);
        $this->assign('t', $t);
        $this->assign('n', $n);
        $this->assign('upload_maxsize', $s);
        $this->assign('type', $type);
        $this->assign('pid', $pid);
        $this->assign('multi', $n == 1 ? 'false' : 'true');
        $this->assign('fileType', $type == 1 ? "'fileType' : 'image'," : '');

        $this->display('upload_box');
    }

    /**
     * 上传文件
     */
    public function upload() {
        $filename = 'filename';
        $type = isset($_POST['type']) ? intval($_POST['type']) : 1;
        $module = isset($_POST['module']) ? htmlspecialchars($_POST['module']) : '';
        $option = array();
        if ($type == 1) {
            $option['allowtype'] = array('gif', 'jpg', 'png', 'jpeg');
        } else {
            $option['allowtype'] = $this->_get_upload_types();
        }
        $upload = new upload($option);
        if ($upload->uploadfile($filename)) {
            $fileinfo = $upload->getnewfileinfo();
            $fileinfo['module'] = $module;
            $fileinfo['originname'] = safe_replace($fileinfo['originname']);
            $fileinfo['thumb'] = 0;
            $this->_att_write($fileinfo);
            $arr = array(
                'status' => 1,
                'msg' => $fileinfo['fileurl'] . $fileinfo['filename'],
                'title' => $fileinfo['originname'],
                'size' => $fileinfo['filesize'],
                'filetype' => $fileinfo['filetype']
            );
            return_json($arr);
        } else {
            $arr = array(
                'status' => 0,
                'msg' => $upload->geterrormsg()
            );
            return_json($arr);
        }
    }

    /**
     * 图像裁剪
     */
    public function img_cropper() {
        $root_path = SITE_PATH == '/' ? ROOT_PATH : str_replace(SITE_PATH, '', str_replace('\\', '/', ROOT_PATH));
        if (isset($_POST['filepath'])) {
            $x = $_POST['x'];
            $y = $_POST['y'];
            $w = $_POST['w'];
            $h = $_POST['h'];
            $image = new \ticky\image();
            $filepath = SITE_PATH . 'runtime/uploads/' . date('Ym/d/');
            $filename = date("ymdhis") . rand(100, 999);
            $filetype = fileext($_POST['filepath']);
            $fileinfo = $image->crop($root_path . $_POST['filepath'], $root_path . $filepath . $filename . '.' . $filetype, $w, $h, $x, $y);
            if ($fileinfo) {
                $fileinfo['module'] = 'admin';
                $fileinfo['originname'] = basename($_POST['filepath']);
                $fileinfo['filepath'] = $filepath;
                $fileinfo['filename'] = $filename . '.' . $filetype;
                $fileinfo['filesize'] = $fileinfo['size'];
                $fileinfo['filetype'] = $filetype;
                $fileinfo['thumb'] = 1;
                $this->_att_write($fileinfo);
                return_json(array('status' => 1, 'filepath' => $fileinfo['filepath'] . $fileinfo['filename']));
            } else {
                return_json(array('status' => 0));
            }
        }
        $filepath = isset($_GET['f']) ? base64_decode($_GET['f']) : showmsg(L('lose_parameters'), 'stop');
        if (strpos($filepath, 'http:') || !is_file($root_path . $filepath)) {
            runlog('att_api', '请选择本地已存在的图像' . $root_path . $filepath);
            showmsg('请选择本地已存在的图像！', 'stop');
        }
        $spec = isset($_GET['spec']) ? intval($_GET['spec']) : 1;
        $cid = isset($_GET['cid']) ? $_GET['cid'] : 'thumb';
        switch ($spec) {
            case 1:
                $spec = '3 / 2';
                break;
            case 2:
                $spec = '4 / 3';
                break;
            case 3:
                $spec = '1 / 1';
                break;
            default:
                $spec = '3 / 2';
        }

        $this->assign('filepath', $filepath);
        $this->display('cropper_box');
    }

    /**
     * 上传附件写入数据库
     */
    private function _att_write($fileinfo) {
        $arr = array();
        // strlen($fileinfo['originname']) < 50 ? $fileinfo['originname'] : $fileinfo['filename'];
        $arr['uid'] = session('uid');
        $arr['dateline'] = time();
        $arr['filename'] = $fileinfo['filename'];
        $arr['filetype'] = $fileinfo['filetype'];
        $arr['filesize'] = $fileinfo['filesize'];
        $arr['attachment'] = $fileinfo['filepath'];
        $arr['isimage'] = in_array($fileinfo['filetype'], array('gif', 'jpg', 'png', 'jpeg')) ? 1 : 0;
        $arr['thumb'] = $fileinfo['thumb'];
        $arr['remote'] = 0;
        $arr['downcount'] = 0;
        $arr['contentid'] = 0;
        $arr['location'] = '';
        db('attachment')->insert($arr);
    }

    /**
     * 获取上传类型
     */
    private function _get_upload_types() {
        $arr = explode('|', get_config('upload_types'));
        $allow = array('gif', 'jpg', 'png', 'jpeg', 'zip', 'rar', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'mp4', 'avi', 'wmv', 'rmvb', 'flv', 'mp3', 'wma', 'wav', 'amr', 'ogg');
        foreach ($arr as $key => $val) {
            if (!in_array($val, $allow))
                unset($arr[$key]);
        }

        return $arr;
    }

}
